package com.baomidou.mybatisplus.samples.quickstart.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {

    private static final String ALLOWED_EXTENSION = ".pdf";
    private static final String UPLOAD_DIR = "uploads"; // 指定上传目录

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @PostMapping("/upload")
    public Map<String, Object> upload(MultipartFile file, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String originalFilename = file.getOriginalFilename();

        if (!originalFilename.endsWith(ALLOWED_EXTENSION)) {
            result.put("status", "error");
            result.put("msg", "error filetype");
            return result;
        }

        String dateStr = sdf.format(new Date());
        String realPath = request.getServletContext().getRealPath("/") + File.separator + UPLOAD_DIR + File.separator + dateStr;
        File destDir = new File(realPath);

        if (!destDir.exists() && !destDir.mkdirs()) {
            result.put("status", "error");
            result.put("msg", "Failed to create directory for upload.");
            return result;
        }

        String newFileName = UUID.randomUUID().toString() + ALLOWED_EXTENSION;
        Path filePath = Paths.get(realPath, newFileName);

        try {
            Files.copy(file.getInputStream(), filePath);
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + UPLOAD_DIR + "/" + dateStr + "/" + newFileName;
            result.put("status", "success");
            result.put("url", url);
        } catch (IOException e) {
            result.put("status", "error");
            result.put("msg", e.getMessage());
            // 记录异常日志
            // logger.error("File upload failed.", e);
        }
        return result;
    }
}